<script setup>
import {useSocket} from "@/socket.js";
import {ref} from "vue";

const socket = useSocket()
const remoteAudioElement = ref()
const isRecording = ref(false)
const stream = ref()
const peerConnection = new RTCPeerConnection()

let mediaContainer = {
  audio: {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true
  },
  video: false
}

const remoteMediaStream = new MediaStream()

const joinChat = async () => {
  if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.log('无法获取麦克风')
    return false
  }

  try {
    stream.value = await navigator.mediaDevices.getUserMedia(mediaContainer)
    console.log('获取音频流成功:', stream.value)
    stream.value.getTracks().forEach(track => {
      peerConnection.addTrack(track, stream.value)
    })

    let offerSdp = await peerConnection.createOffer({
      offerToReceiveAudio: 1
    })

    await peerConnection.setLocalDescription(offerSdp)
    socket.emit('offerSdp', offerSdp)

    isRecording.value = true

  } catch (err) {
    console.error('获取麦克风失败:', err)
    alert('无法访问麦克风，请检查浏览器权限设置')
  }
}

const stopChat = () => {
  if (stream.value) {

    stream.value.getTracks().forEach(track => {
      track.stop()
    })
    stream.value = null
  }
  isRecording.value = false
}

const toggleMute = () => {
  if (stream.value) {
    const audioTracks = stream.value.getAudioTracks()
    audioTracks.forEach(track => {
      track.enabled = !track.enabled
    })
  }
}

socket.on('offerSdp', async offerSdp => {
  await peerConnection.setRemoteDescription(offerSdp)
  const answerSdp = await peerConnection.createAnswer()
  await peerConnection.setLocalDescription(answerSdp)
  socket.emit('answerSdp', answerSdp)
})

socket.on('answerSdp', async answerSdp => {
  console.log('answer: '+answerSdp)
  await peerConnection.setRemoteDescription(answerSdp)
})

peerConnection.onicecandidate = (event) =>{
  if(event.candidate) {
    socket.emit('icecandidate', event.candidate)
  }
}

socket.on('icecandidate', async icecandidate => {
  await peerConnection.addIceCandidate(icecandidate)
})


peerConnection.ontrack = (event) => {
  remoteMediaStream.addTrack(event.track)
  remoteAudioElement.value.srcObject = remoteMediaStream
}

</script>

<template>
  <div class="d-flex">
    <div class="user-list">
      语音频道
    </div>
    <div>

      <audio
          autoplay
          ref="remoteAudioElement"
      />

      <div class="controls">
        <button
            v-if="!isRecording"
            class="btn btn-outline-primary"
            @click="joinChat"
        >
          Join Voice
        </button>
        <button
            v-else
            class="btn btn-outline-danger"
            @click="stopChat"
        >
          Leave Voice
        </button>
        <button
            v-if="isRecording"
            class="btn btn-outline-secondary"
            @click="toggleMute"
        >
          Toggle Mute
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-list {
  padding: 10px;
  width: 200px;
}

.controls {
  margin-top: 10px;
}

.controls button {
  margin-right: 10px;
}
</style>